package com.bjsxt.utils;

import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class CommonsMailSender {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${spring.mail.username}")
    private String from;

    public void send(String to,String subject,String content) throws MessagingException, IOException, TemplateException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,false,"utf-8");
        helper.setTo(to);
        helper.setFrom(from);
        helper.setSubject(subject);
        Template template = freeMarkerConfigurer.getConfiguration().getTemplate("order.ftl");
        Map<String,Object> model = new HashMap<>();
        model.put("orderId",content);
        String freemarkString = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
        helper.setText(freemarkString,true);
        javaMailSender.send(mimeMessage);
    }
}
